package com.eds.controller;


import com.eds.exception.BusException;
import com.eds.log.LogUtil;
import com.eds.pojo.BaseResult;
import com.eds.pojo.CodeEnum;
import com.eds.service.AiService;
import com.pojo.AiConversation;
import com.pojo.AiMessage;
import com.pojo.Course;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * AI聊天功能控制器
 * 提供AI对话相关的API接口
 */
@RestController
@RequestMapping("/chat")
public class AiController {

    /**
     * 注入AI服务接口
     */
    @Autowired
    private AiService aiService;


    /**
     * 发送消息到AI并获取回复
     *
     * @param request 包含用户消息和会话ID的请求
     * @return 包含AI回复内容的响应对象
     */
    @PostMapping("/sendMessage")
    public BaseResult<Map<String, Object>> sendMessage(@RequestBody Map<String, Object> request) {
        // 获取请求中的消息内容和会话ID
        String message = (String) request.get("message");
        //判断是否有conversationId，如果是String类型转换为Long类型
        Long conversationId = request.get("conversationId") != null ?
                Long.valueOf(request.get("conversationId").toString()) : null;
        String token = (String) request.get("token");
        LogUtil.info(AiController.class, "会话ID = " + conversationId, "用户发送的信息为：" + message, "Token为：" + token);
        // 调用服务处理消息并获取AI回复
        Map<String, Object> response = aiService.processMessage(message, conversationId, token);
        LogUtil.info(AiController.class, conversationId + "会话的" + "人工智能的回答为：" + response);
        if (response.isEmpty()) {
            throw new BusException(CodeEnum.AI_TALK_ERROR.getCode(), CodeEnum.AI_TALK_ERROR.getMessage());
        }
        // 返回包含AI回复的响应对象
        return BaseResult.ok("AI响应成功！", response);
    }

    /**
     * 获取用户的所有对话列表
     *
     * @param token 用户认证令牌
     * @return 包含对话列表的响应对象
     */
    @GetMapping("/conversations")
    public BaseResult<Map<String, Object>> getConversations(@RequestHeader("Authorization") String token) {
        // 调用服务获取用户的所有对话
        List<AiConversation> conversations = aiService.getUserConversations(token);
        // 构建响应对象
        Map<String, Object> response = new HashMap<>();
        response.put("code", 200);
        response.put("message", "获取会话列表成功");
        response.put("data", conversations);
        if (conversations == null) {
            return BaseResult.error(CodeEnum.GET_USER_ALL_CONVERSATION_LIST_ERROR);
        }
        return BaseResult.ok("获取用户的所有对话列表成功！", response);
    }

    /**
     * 获取特定对话的消息历史
     *
     * @param conversationId 对话ID
     * @param token          用户认证令牌
     * @return 包含消息历史的响应对象
     */
    @GetMapping("/history/{conversationId}")
    public BaseResult<Map<String, Object>> getConversationHistory(
            @PathVariable Long conversationId,
            @RequestHeader("Authorization") String token) {
        // 调用服务获取对话的消息历史
        List<AiMessage> messages = aiService.getConversationHistory(conversationId, token);
        // 构建响应对象
        Map<String, Object> response = new HashMap<>();
        response.put("code", 200);
        response.put("message", "获取会话历史成功");
        response.put("data", messages);
        if (messages == null) {
            return BaseResult.error(CodeEnum.GET_APPOINT_CONVERSATION_LIST_ERROR);
        }
        return BaseResult.ok("获取特定对话的消息历史成功！", response);
    }

    /**
     * 创建新的对话
     *
     * @param request 包含对话标题的请求
     * @param token   用户认证令牌
     * @return 包含新对话ID的响应对象
     */
    @PostMapping("/newConversation")
    public BaseResult<Map<String, Object>> createConversation(
            @RequestBody Map<String, String> request,
            @RequestHeader("Authorization") String token) {
        // 获取请求中的对话标题
        String title = request.get("title");
        // 调用服务创建新对话
        Long conversationId = aiService.createConversation(title, token);
        // 构建响应对象
        Map<String, Object> response = new HashMap<>();
        response.put("code", 200);
        response.put("message", "创建会话成功");
        response.put("data", conversationId);
        if (conversationId == null) {
            return BaseResult.error(CodeEnum.CREATE_CONVERSATION_ERROR);
        }
        return BaseResult.ok("新增会话成功！", response);
    }

    /**
     * 删除对话
     *
     * @param conversationId 要删除的对话ID
     * @param token          用户认证令牌
     * @return 操作结果响应对象
     */
    @DeleteMapping("/delConversation/{conversationId}")
    public BaseResult<Map<String, Object>> deleteConversation(
            @PathVariable Long conversationId,
            @RequestHeader("Authorization") String token) {
        // 调用服务删除对话
        boolean success = aiService.deleteConversation(conversationId, token);

        // 构建响应对象
        Map<String, Object> response = new HashMap<>();
        if (success) {
            response.put("code", 200);
            response.put("message", "删除会话成功");
        } else {
            response.put("code", 400);
            response.put("message", "删除会话失败");
        }
        if (success == false) {
            return BaseResult.error(CodeEnum.DELETE_CONVERSATION_ERROR);
        }
        return BaseResult.ok("删除会话成功！", response);
    }
    //异步更新热门用户推荐


    //系统推荐的热门课程
    @GetMapping("/hotRecommendations")
    public BaseResult<List<Course>> getHotRecommendations() {

        List<Course> courses = aiService.hotCacheChangeRecommendationDtoToCourse();
        return BaseResult.ok("获取热门推荐成功！", courses);
    }

    //用户推荐的课程
    @GetMapping("/userRecommendations")
    public BaseResult<List<Course>> getUserRecommendations(@RequestHeader("Authorization") String token) {
        List<Course> courses = aiService.userCacheChangeRecommendationDtoToCourse(token);
        return BaseResult.ok("获取用户推荐成功！", courses);
    }

    //用户推荐的课程
    @GetMapping("/happyRecommendations")
    public BaseResult getHappyRecommendations() {
        String happy = aiService.happyCacheChangeRecommendationDtoToCourse();
        if (happy == null) {
            return BaseResult.error(CodeEnum.HAPPY_RECOMMENDATIONS_ERROR);
        }
        return BaseResult.ok("获取开心推荐成功！", happy);
    }
}